import React, { Component } from 'react';
import Taro from '@tarojs/taro';
import {connect} from 'react-redux';
import {View, Image, Text} from '@tarojs/components';
import {AtIcon} from 'taro-ui';
import {GetRequest} from "../../utils/tools";
import {http} from "../../utils/http";
import {newHttp} from "../../utils/request";
import {user} from '../../utils/user.service';
import {TARO_ENV, RESOURCE_URL, FETCH_WIFI_BINDSELLERID} from "../../constants/api";
import "./index.scss";

const connectImg_ing = "https://resource.ivcheng.com/upload/images/20220903/1662184134310_703.png";
const connectImg_finish = "https://resource.ivcheng.com/upload/images/20220903/1662184311488_254.png";

export default class WiFiConnect extends Component {
    constructor(props) {
		super(props);
		this.state = {
			loginStatus: false,
			wifiName: "",
			connectStatus: "",
			tipMsg: ""
		};
	}

    async UNSAFE_componentWillMount() {}

    async componentDidShow() {
		const loginStatus = await user.checkLogin();
		console.log("loginStatus ------------- : ", loginStatus);

		if(!loginStatus) {
			await Taro.navigateTo({
				url: '/main/login/login'
			})
		}else {
			Taro.showLoading({title: "请稍等", mask: true});
			const _this = this;
			const reqParam = Taro.getCurrentInstance().router.params;
			console.log("req : ", reqParam);
			const { name: params } = reqParam;
			const paramArr = params.split("|");
			const name = paramArr.length > 0 ? paramArr[0] : "";
			const pass = paramArr.length > 1 ? paramArr[1].slice(5) : "";
			const ssid = paramArr.length > 2 ? paramArr[2].slice(5) : "";
			const sellerId = paramArr.length > 3 ? paramArr[3].slice(9) : "";

			this.setState({ wifiName: name });
			const result = await newHttp.catchPost(FETCH_WIFI_BINDSELLERID, {sellerId}, true, "needPage");
			console.log("bind sellerId result -------- : ", result);
			this.setState({ tipMsg: result.data });

			Taro.showLoading({title: "连接中", mask: true});
			wx.startWifi({
				success: (res) => {
					wx.connectWifi({
						SSID: ssid,
						password: pass,
						success(res) {
							console.log("连接结果 - success : ", res);
							// {errMsg: "connectWifi:ok"}
							if(res && res.errMsg === "connectWifi:ok") {
								_this.setState({ connectStatus: "success" });
								wx.onWifiConnected((ress) => {
									console.log("监听连接上 Wi-Fi 的事件 - 0 : ", res);
								})
							}
						},
						fail(res) {
							console.log("连接结果 - fail : ", res);
							if(res && res.errMsg === "connectWifi:fail") {
								_this.setState({ connectStatus: "fail" });
							}
						},
						complete(res) {
							console.log("连接结束 - fail : ", res);
							let tipContent = "";
							// 用户拒绝授权链接 Wi-Fi
							if(res.errCode == 12007) {
								Taro.navigateBack();
							}
							// Android
							if(res.errCode === 12010) {
								tipContent = "密码错误或其他未知错误！";
							}
							// iOS
							if(res.errCode === 12014) {
								tipContent = "密码错误！";
							}
							if(tipContent) {
								Taro.showModal({
									title: '提示',
									content: tipContent,
									showCancel: false,
									success: function (res) {
										Taro.navigateBack();
									}
								})
							}
							wx.onWifiConnected((ress) => {
								console.log("监听连接上 Wi-Fi 的事件 - 1 : ", res);
							})
							Taro.hideLoading();
						}
					})
				}
			})
		}
	}
    gotoIndex = () => {
		Taro.navigateTo({
            url: `/pages/index/index`
        })
	}

    render() {
		const { loginStatus, wifiName, connectStatus, tipMsg } = this.state;

		return (
			<View className="wifi-connect-page">
				{/*<View className="tip-msg">{tipMsg}</View>*/}
				{
					connectStatus !== "success" ?
					<View className="connect-tip">
						<Image src={connectImg_ing} className="connect-img connect-ing" />
						<Text>正在连接 {wifiName} ...</Text>
					</View>
					:
					<View className="connect-tip connect-success">
						<Image src={connectImg_finish} className="connect-img connect-finish" />
						<Text>连接完成，请确认是否已成功连接 {wifiName}</Text>
					</View>
				}
				<View className="index-btn">
					<Navigator url='/pages/index/index' openType='switchTab'>
						返回首页
					</Navigator>
				</View>
			</View>
		)
	}
}
